//
//  PTAddressView.m
//  PotentialTraining
//
//  Created by Mr.Wang on 2018/11/4.
//  Copyright © 2018 admin. All rights reserved.
//

#import "PTAddressView.h"


@interface PTAddressView()

@property (nonatomic, strong) NSString *cellTag;

@property (nonatomic, strong) NSMutableArray *proArr;

@property (nonatomic, strong) NSMutableArray *cityArr;

@property (nonatomic, strong) NSMutableArray *countyArr;

@property (nonatomic, assign) NSInteger clickNum;


@property (nonatomic, copy) NSString *proId;

@property (nonatomic, copy) NSString *cityId;

@property (nonatomic, copy) NSString *countyId;

@property (nonatomic, copy) NSString *proName;

@property (nonatomic, copy) NSString *cityName;

@property (nonatomic, copy) NSString *countyName;

@property (nonatomic, assign) BOOL clickPro;

@property (nonatomic, assign) BOOL clickCity;

@end

@implementation PTAddressView



- (instancetype) initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        
        self.backgroundColor = [UIColor blackColor];
        
        self.cellTag = @"AddIdentifier";
        self.clickNum = 0;
        
        [self layoutSubControls];
        
        [self loadAddressData];
        
        [self initDataSource];
    }
    
    return self;
}

- (void) initDataSource {
    
    self.proArr = [NSMutableArray array];
    self.cityArr = [NSMutableArray array];
    self.countyArr = [NSMutableArray array];
}

- (void) loadAddressData {
    
    
    NSString *getUrl = [NSString stringWithFormat:@"%@%@", [[VersionManager shareManager] currentVersion], kPRO];
    kDLog(@"获取省接口是：%@", getUrl);
    
    [CHNetWorkSingleton requestAFWithURL:getUrl params:nil httpMethod:@"GET" isHUD:NO finishBlock:^(id result) {
        
        NSLog(@"获取省接口返回的信息是：%@", result);
        NSArray *proArray = result[@"data"];
        NSString *code = result[@"code"];
        
        if ([code isEqualToString:@"11"] && proArray != nil) {
            
            self.proArr = [NSMutableArray arrayWithArray:proArray];
            [self.addressTable reloadData];
        }
    } errorBlock:^(NSError *error) {
        
        kDLog(@"获取省失败，错误是：%@", error);
    }];
}

- (void) layoutSubControls {
    
    UIButton *cancelBtn = [UIButton buttonWithType:0];
    cancelBtn.frame = CGRectMake(0, 0, 60, 40);
    [cancelBtn addTarget:self action:@selector(xxxxxxxxxx) forControlEvents:UIControlEventTouchUpInside];
    [cancelBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [cancelBtn setTitle:@"返回" forState:UIControlStateNormal];
    cancelBtn.backgroundColor = [UIColor orangeColor];
    [self addSubview:cancelBtn];
    
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(cancelBtn.frame), self.frame.size.width, self.frame.size.height - 40) style:UITableViewStylePlain];
    tableView.backgroundColor = [UIColor whiteColor];
    tableView.rowHeight = 80;
    tableView.delegate = self;
    tableView.dataSource = self;
    [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:self.cellTag];
    [self addSubview:tableView];
    self.addressTable = tableView;
    
}
- (void) xxxxxxxxxx{
    
    if (self.clickNum == 0) {
        
        NSLog(@"地址弹窗消失");
        [self dismissSelf];
    } else if (self.clickNum == 1) {
        self.clickNum--;
        NSLog(@"点击返回按钮，请求省信息");
        [self loadAddressData];
    } else if (self.clickNum == 2) {
        self.clickNum--;
        NSLog(@"点击返回按钮，请求市信息");
        [self loadCityDataWithProId:self.proId];
    }
}

- (void) loadCityDataWithProId:(NSString *)proId {
    
    NSString *getUrl = [NSString stringWithFormat:@"%@%@province_id/%@", [[VersionManager shareManager] currentVersion], kCITY, proId];
    kDLog(@"获取市接口是：%@", getUrl);
    
    [CHNetWorkSingleton requestAFWithURL:getUrl params:nil httpMethod:@"GET" isHUD:NO finishBlock:^(id result) {
        
        NSLog(@"获取市接口返回的信息是：%@", result);
        NSArray *proArray = result[@"data"];
        NSString *code = result[@"code"];
        if ([code isEqualToString:@"11"] && proArray != nil) {
            
            [self.cityArr removeAllObjects];
            self.cityArr = [NSMutableArray arrayWithArray:proArray];
            
            if (self.clickPro == YES) {
                self.clickNum ++;
            }
            [self.addressTable reloadData];
        }
    } errorBlock:^(NSError *error) {
        
        kDLog(@"获取市失败，错误是：%@", error);
    }];
}

- (void) loadCountyDataWithCityId:(NSString *)CityId {
    
    NSString *getUrl = [NSString stringWithFormat:@"%@%@city_id/%@", [[VersionManager shareManager] currentVersion], kAREA, CityId];
    kDLog(@"获取县接口是：%@", getUrl);
    
    [CHNetWorkSingleton requestAFWithURL:getUrl params:nil httpMethod:@"GET" isHUD:NO finishBlock:^(id result) {
        
        NSLog(@"获取县接口返回的信息是：%@", result);
        NSArray *proArray = result[@"data"];
        NSString *code = result[@"code"];
        
        if ([code isEqualToString:@"11"] && proArray != nil) {
            
            [self.countyArr removeAllObjects];
            self.countyArr = [NSMutableArray arrayWithArray:proArray];
            
            if (self.clickCity ==YES) {
                self.clickNum ++;
            }
            [self.addressTable reloadData];
        }
    } errorBlock:^(NSError *error) {
        
        kDLog(@"获取县失败，错误是：%@", error);
    }];
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (self.clickNum == 0) {
        return self.proArr.count;
    } else if (self.clickNum == 1) {
        return self.cityArr.count;
    } else {
        return self.countyArr.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:self.cellTag];
    
    NSDictionary *dic;
    if (self.clickNum == 0) {
        dic = self.proArr[indexPath.row];
    } else if (self.clickNum == 1) {
        dic = self.cityArr[indexPath.row];
    } else {
        dic = self.countyArr[indexPath.row];
    }
    
    cell.textLabel.text = [NSString stringWithFormat:@"%@", dic[@"name"]];
    return cell;
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary *dic;
    //013
    if (self.clickNum ==0) {
        dic = self.proArr[indexPath.row];
        NSString *proId = dic[@"province_id"];
        self.proId = proId;
        self.proName = dic[@"name"];
        
        self.clickPro = YES;
        [self loadCityDataWithProId:proId];
    } else if (self.clickNum == 1) {
        dic = self.cityArr[indexPath.row];
        NSString *cityId = dic[@"city_id"];
        self.cityId = cityId;
        self.cityName = dic[@"name"];
        
        self.clickCity = YES;
        self.clickPro = NO;
        [self loadCountyDataWithCityId:cityId];
    }
    
    if (self.clickNum == 2) {
        
//        self.clickCity = NO;
//        self.clickPro = NO;
        
        dic = self.countyArr[indexPath.row];
        NSString *countyId = dic[@"district_id"];
        self.countyId = countyId;
        self.countyName = dic[@"name"];
        
        [self dismissSelf];
        
        //传出去选择的省市县
        [self qweqweqwe];
        return;
    }
    
}

- (void) qweqweqwe {
    
    
    NSArray *addArr = @[
                        @{@"name" : self.proName, @"id" : self.proId},
                        @{@"name" : self.cityName, @"id" : self.cityId},
                        @{@"name" : self.countyName, @"id" : self.countyId}
                        ];
//    NSLog(@"选择的地区信息是：%@", addArr);
    if ([self.AddressDelegate respondsToSelector:@selector(selecteAddress:)]) {
        [self.AddressDelegate selecteAddress:addArr];
    }
}


- (void) dismissSelf {
    
    [UIView animateWithDuration:0.3 animations:^{
        
        self.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 500);
    } completion:^(BOOL finished) {
        
        [self removeFromSuperview];
    }];
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
